package com.woniuxy.gateway.exception;

import cn.hutool.json.JSONUtil;
import com.woniuxy.gateway.util.Result;
import com.woniuxy.core.exception.PawnException;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关异常类
 */
@Component
public class GatewayException implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        Result result = Result.fail(500,"出现异常");
        if (ex instanceof PawnException){
            PawnException me = (PawnException) ex;
            result = result.fail(me.getCode(),me.getMessage());
        }
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        String json = JSONUtil.parse(result).toString();
        return exchange.getResponse().writeWith(Mono.fromSupplier(()->{
            return exchange.getResponse().bufferFactory().wrap(json.getBytes());
        }));
    }
}
